<template>
  <div>
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      width="500px"
      @close="close"
    >
      <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
        <el-form-item label="用户名" prop="name">
          <el-input v-model.trim="form.name" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model.trim="form.account" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item
          v-if="!form.id || isSuper"
          label="密码"
          :prop="form.id ? '' : 'password'"
        >
          <el-input v-model.trim="form.password" type="password" />
        </el-form-item>
        <el-form-item v-if="form.is_super !== 1" label="角色" prop="role_ids">
          <el-select v-model="form.role_ids" multiple collapse-tags>
            <el-option
              v-for="(item, index) in allRoles"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.is_super !== 1" label="状态" prop="status">
          <el-radio v-model="form.status" :label="1">正常</el-radio>
          <el-radio v-model="form.status" :label="0">禁用</el-radio>
        </el-form-item>
      </el-form>

      <div class="text-red-600">
        提示: 密码需大于等于8位且包含数字和大小字母
      </div>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogResetPswFormVisible"
      :title="'重设密码'"
      width="500px"
      @close="close"
    >
      <el-form
        ref="restFormRef"
        label-width="80px"
        :model="resetForm"
        :rules="rules"
      >
        <el-form-item label="原密码" prop="old_password">
          <el-input v-model.trim="resetForm.old_password" type="password" />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model.trim="resetForm.new_password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model.trim="resetForm.confirm_password" type="password" />
        </el-form-item>
      </el-form>
      <div class="text-red-600">
        提示: 密码需大于等于8位且包含数字和大小字母
      </div>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="resetPsw">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { doEdit, doAdd, resetPassword } from '@/api/adminUser'
  import { getAllList } from '@/api/role'
  import { nextTick } from 'vue'
  import { showLoading, closeLoading } from '@/utils/newloading'
  import { useUserStore } from '@/store/modules/user'
  const validatePass = (rule, value, callback) => {
    const res = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/
    if (value === '') {
      callback(new Error('请输入密码'))
    } else {
      if (!res.test(value)) {
        callback(new Error('密码不符合规则'))
      } else {
        callback()
      }
    }
  }

  const validateNewPass = (rule, value, callback) => {
    const res = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/
    if (!res.test(value)) {
      callback(new Error('密码不符合规则'))
    } else {
      callback()
    }
  }

  const validateConfirmPass = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请确认密码'))
    } else if (value !== resetForm.new_password) {
      callback(new Error('请确保两次密码一致!'))
    } else {
      callback()
    }
  }

  export default defineComponent({
    name: 'AdminUserEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        restFormRef: null,
        form: {
          name: '',
          account: '',
          password: '',
          status: 1,
          role_ids: [],
          role_id: '',
        },
        isSuper: false,
        defaultProp: {
          children: 'children',
          value: 'value',
          label: 'department_name',
        },
        resetForm: {
          old_password: '',
          new_password: '',
          confirm_password: '',
        },
        rules: {
          name: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
          account: [{ required: true, trigger: 'blur', message: '请输入账号' }],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePass,
            },
          ],
          old_password: [
            { required: true, trigger: 'blur', message: '请输入密码' },
          ],
          new_password: [
            {
              required: true,
              trigger: 'blur',
              validator: validateNewPass,
            },
          ],
          confirm_password: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入密码',
              validator: validateConfirmPass,
            },
          ],
          status: [{ required: true, trigger: 'blur', message: '请选择状态' }],
          role_ids: [
            { required: true, trigger: 'blur', message: '请选择角色' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        dialogResetPswFormVisible: false,
        allRoles: [],
        list: [],
      })

      const getAllRoles = async () => {
        const { data } = await getAllList()

        state.allRoles = data
        console.log('state.allRoles', state.allRoles)
      }

      const showEdit = async (row) => {
        showLoading()
        await getAllRoles()
        closeLoading()
        state.dialogFormVisible = true
        nextTick(() => {
          if (!row) {
            state.title = '添加'
          } else {
            state.title = '编辑'
            state.form = JSON.parse(JSON.stringify(row))
            if (state.form.role_id) {
              state.form.role_ids = state.form.role_id
                .split(',')
                .map((item) => {
                  item = Number(item)
                  return item
                })
            }
            console.log('state.form.role_ids', state.form.role_ids)
            console.log('ceshi1', ''.split(','))
            const res = useUserStore()
            if (res.admin.is_super == 1) {
              state.isSuper = true
            }
          }
        })
      }
      const close = () => {
        state['formRef']?.resetFields()
        state['restFormRef']?.resetFields()
        state.form = {
          role_id: '',
        }
        state.isSuper = false
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            state.form.role_id = state.form.role_ids.join(',')
            if (state.form.id) {
              const { msg } = await doEdit(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
            } else {
              const { msg } = await doAdd(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
            }

            emit('fetch-data')
            close()
          }
        })
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
        getAllRoles,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .text-red-600 {
    color: rgba(220, 38, 38, var(--tw-text-opacity));
    text-align: center;
    --tw-text-opacity: 1;
  }
</style>
